package cn.sumpu.app.guoguojie.biz.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.biz.MailBiz;
import cn.sumpu.app.guoguojie.biz.MemberBiz;
import cn.sumpu.app.guoguojie.constant.FamilyRole;
import cn.sumpu.app.guoguojie.constant.Sex;
import cn.sumpu.app.guoguojie.dao.DetailDao;
import cn.sumpu.app.guoguojie.dao.FamilyDao;
import cn.sumpu.app.guoguojie.dao.MemberDao;
import cn.sumpu.app.guoguojie.domain.Detail;
import cn.sumpu.app.guoguojie.domain.Family;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.Ext.Baby;
import cn.sumpu.app.guoguojie.domain.Ext.MemberExt;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.IdGenerator;
import cn.sumpu.app.guoguojie.util.PageModel;

public class MemberBizImpl implements MemberBiz {

	private MemberDao memberDao;
	private DetailDao detailDao;
	private FamilyDao familyDao;
	@Autowired
	private MailBiz mailBiz;
	@Autowired
	private ImageBiz imageBiz;
	
	private String imageServer;
	
	public String getImageServer() {
		return imageServer;
	}

	public void setImageServer(String imageServer) {
		this.imageServer = imageServer;
	}

	public void setMailBiz(MailBiz mailBiz) {
		this.mailBiz = mailBiz;
	}

	public void setFamilyDao(FamilyDao familyDao) {
		this.familyDao = familyDao;
	}

	public void setMemberDao(MemberDao memberDao) {
		this.memberDao = memberDao;
	}

	public void setDetailDao(DetailDao detailDao) {
		this.detailDao = detailDao;
	}

	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public Member login(Member member) throws AppBusinessException {
		return null;
	}

	@Override
	public Member login(Family family, Member member)
			throws AppBusinessException {

		return null;
	}

	public List<Member> getMemberPwdEmail(String pwd, String email)
			throws AppBusinessException {
		if (Common.empty(email))  
			return null;
		pwd = Common.md5(Common.md5(pwd));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("password", pwd);
		map.put("email", email);
		List<Member> mList = memberDao.getMemberList(map);
		return mList;
	}

	@Override
	public List<Member> getMemberPwdDoorplate(String pwd, String doorplate)
			throws AppBusinessException {
		if (Common.empty(doorplate))
			return null;
		pwd = Common.md5(Common.md5(pwd));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("password", pwd);
		map.put("family", doorplate);
		List<Member> mList = memberDao.getMemberList(map);
		return mList;
	}

	@Override
	public Member getMemberPwdDoorplateEmail(String pwd, String doorplate,
			String email) throws AppBusinessException {
		if (Common.empty(doorplate))
			return null;
		pwd = Common.md5(Common.md5(pwd));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("password", pwd);
		map.put("family", doorplate);
		map.put("email", email);
		List<Member> mList = memberDao.getMemberList(map);
		if (mList != null && mList.size() > 0)
			return mList.get(0);
		return null;
	}

	@Override
	public Member getMemberEmail(String email) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("email", email);
		List<Member> mList = memberDao.getMemberList(map);
		if (mList != null && mList.size() > 0)
			return mList.get(0);
		return null;
	}

	@Override
	public List<Member> getMemberPwdMobile(String pwd, String mobile)
			throws AppBusinessException {
		if (Common.empty(mobile))
			return null;
		pwd = Common.md5(Common.md5(pwd));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("password", pwd);
		map.put("mobilephone", mobile);
		List<Member> mList = memberDao.getMemberList(map);
		return mList;
	}

	@Override
	public List<Member> login(String loginName, String pwd)
			throws AppBusinessException {
		if (Common.empty(loginName)) 
			return null;  

		List<Member> m = getMemberPwdDoorplate(pwd, loginName);
		// 门牌号不存在email登录
		if (m == null || m.size()<1) {
			m = getMemberPwdEmail(pwd, loginName);
		}
		// 门牌号和email都不存在则手机号码登录
		if (m == null || m.size()<1) {
			m = getMemberPwdMobile(pwd, loginName);
		}

		return m;
	}

	@Override
	public void updateMember(Member member) throws AppBusinessException {
		memberDao.updateMember(member);
	}
	
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void setAccount(Member member) throws AppBusinessException {
		String hostPwd = memberDao.getHostPwdByDoorplate(member.getFamily());
		//如果是户主
		if(member.getIsHost()){
			//如果其他成员和户主使用同一把钥匙
			List<Member> parentList = memberDao.getParentListByDoorplate(member.getFamily());
			if(parentList!=null){
				for(Member m:parentList){
					//判断是其他成员
					if(!m.getIdentifier().equals(member.getIdentifier())){
						//判断其他成员是否和户主的密码一样
						if(m.getPassword().equals(hostPwd)){
							m.setPassword(Common.md5(Common.md5(member.getPassword())));
							memberDao.updateMember(m);
						}
					}
				}
			}
			member.setPassword(Common.md5(Common.md5(member.getPassword())));
			memberDao.updateMember(member);
		}else{
			//如果是和户主使用同一把钥匙
			if(member.getPassword()==null || "".equals(member.getPassword())){
				member.setPassword(hostPwd);
				memberDao.updateMember(member);
			}else{
				member.setPassword(Common.md5(Common.md5(member.getPassword())));
				memberDao.updateMember(member);
			}
		}
	}

	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public Member addMember(String basePath, Member member) throws AppBusinessException {
		String identifier = IdGenerator.createIdentifier();
		String hostPwd = memberDao.getHostPwdByDoorplate(member.getFamily());
		//如果和户主使用不是同一把钥匙
		if(member.getPassword()==null || "".equals(member.getPassword())){
			member.setPassword(hostPwd);
		}
		member.setActiveCode(null);
		member.setIdentifier(identifier);
		if (FamilyRole.FATHER.getValue().equals(member.getRole())) {
			member.setAvatar(Common.AVATAR_MAN_DEFALUT);
		} else if (FamilyRole.MOTHER.getValue().equals(member.getRole())) {
			member.setAvatar(Common.AVATAR_WOMAN_DEFALUT);
		}
		memberDao.insert(member);
		mailBiz.sendEmail(basePath, member);
		Detail detailMember = new Detail();
		detailMember.setMember(identifier);
		// 如果是妈妈角色则将性别是女，否则是男
		detailMember
				.setSex(FamilyRole.MOTHER.getValue().equals(member.getRole()) ? Sex.FEMALE
						.getValue() : Sex.MALE.getValue());
		detailDao.insertDetail(detailMember);
		return member;
	}

	// 保存宝宝信息
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void addBaby(Baby baby) throws AppBusinessException {
		// 如果添加了宝宝
		if (!Common.empty(baby.getBabyName())) {
			Member member = new Member();
			Detail detail = new Detail();
			String id = IdGenerator.createIdentifier();
			member.setUsername(baby.getBabyName());
			member.setRole(FamilyRole.BABY.getValue());
			member.setAvatar(Common.AVATAR_BABY_DEFALUT);
			member.setFamily(baby.getFamily());
			member.setIdentifier(id);
			memberDao.insert(member);

			detail.setSex(baby.getBabySex());
			detail.setBirthday(baby.getBirthday());
			detail.setMember(id);
			detailDao.insertDetail(detail);
		} else if (baby.getBabyList() != null && baby.getBabyList().size() > 0) {
			List<Baby> babyList = baby.getBabyList();
			for (int i = 0; i < babyList.size(); i++) {
				Baby babys = babyList.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("member", babys.getIdentifier());
				Member member = memberDao.getMemberById(babys.getIdentifier());
				Detail detail = detailDao.getDetailList(map).get(0);
				member.setUsername(babys.getBabyName());
				detail.setBirthday(babys.getBirthday());
				detail.setSex(babys.getBabySex());
				memberDao.updateMember(member);
				detailDao.updateDetail(detail);
			}
		}

	}

	@Override
	public PageModel getPageModel(Member member, Integer page)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("family", member.getFamily());
		map.put("username", member.getUsername());
		map.put("email", member.getEmail());
		Integer startId = (page - 1) * Common.PAGE_SIZE;
		map.put("startId", startId);
		map.put("pageSize", Common.PAGE_SIZE);
		List<Member> mList = memberDao.getMemberList(map);
		int count = memberDao.getMemberListCount(map);
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(mList);
		pm.setPageSize(Common.PAGE_SIZE);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + Common.PAGE_SIZE - 1) / Common.PAGE_SIZE);
		return pm;
	}

	@Override
	public MemberExt getBaseInfo(String id) throws AppBusinessException {
		return memberDao.getBaseInfo(id);
	}

	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void saveBaseInfo(MemberExt memberExt) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("identifier", memberExt.getIdentifier());
		map.put("hostName", memberExt.getHostName());
		// FIXME 优化
		memberDao.updateMember(memberDao.getMemberById(memberExt.getIdentifier()));
		Detail d = new Detail();
		d.setBirthday(memberExt.getBirthday());
		d.setProvice(memberExt.getProvice());
		d.setCity(memberExt.getCity());
		d.setDistrict(memberExt.getDistrict());
		d.setAddress(memberExt.getAddress());
		d.setBirthProvice(memberExt.getBirthProvice());
		d.setBirthCity(memberExt.getBirthCity());
		d.setBirthDistrict(memberExt.getBirthDistrict());
		d.setBirthAddress(memberExt.getBirthAddress());
		d.setMember(memberExt.getIdentifier());
		detailDao.updateDetail(d);
		Member m = new Member();
		m.setIdentifier(memberExt.getIdentifier());
		m.setRole(memberExt.getRole());
		memberDao.updateMember(m);
	}
	
	//修改登录用户的信息
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void updateLoginMember(Member member, Detail detail) throws AppBusinessException {
		memberDao.updateMember(member);
		detailDao.updateDetail(detail);
	}

	@Override
	public List<Baby> getBabyList(String member) throws AppBusinessException {

		return memberDao.getBabyList(member);
	}

	@Override
	public Member getMemberById(String id) throws AppBusinessException {
		return memberDao.getMemberById(id);
	}

	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public String cutAvatar(HttpServletRequest request, String srcImg, int xCoords,
			int yCoords, int destWidth, int destHeight, int divWidth,
			int divHeight) throws AppBusinessException { 
		String webAppPath = request.getSession().getServletContext()
				.getRealPath("/");
		Member member = (Member) request.getSession().getAttribute("member");
		String family = member.getFamily();
		String formateDate = Common.getFormatDate(new Date());
		String destDir = webAppPath + File.separator + "pic" + File.separator
				+ "avatar" + File.separator + formateDate + File.separator
				+ family + File.separator;

		String srcImgPath = webAppPath + File.separator + srcImg;

	
		// type代表上传头像的类型1.会员头像 2.家的头像 3.baby头像
		String type = request.getParameter("type");
		String memberId = request.getParameter("memberId");
		
		String imageName = memberId;
		if(!Common.empty(type) && Integer.parseInt(type) == 2){
			imageName = member.getFamily()+"_"+member.getIdentifier();
		}
		String cutUrl = "pic/avatar/" + formateDate + "/" + family + "/" + imageName + ".jpg"+"?tmpId="+Math.random();
		String imageServer = imageBiz.cutAvatar(srcImgPath, destDir, imageName,
				xCoords, yCoords, destWidth, destHeight, divWidth, divHeight,
				120, 120,false);
	//	ImageUtil.cut(srcImgPath, destDir, imageName, xCoords, yCoords,destWidth, destHeight, divWidth, divHeight, 34, 34);
//		如果是上传的文件，上传完成后删除
		/*String photoType = request.getParameter("photoType");
		if (!Common.empty(photoType)) {
			if (Integer.parseInt(photoType) == 1) {
				File f = new File(srcImgPath);
				if (f.exists()) {
					f.delete();
				}
			}
		}*/
		
		if (Common.empty(type)) {
			type = "1";
		}
		if (Integer.parseInt(type) == 1) {
			if(member.getIdentifier().equals(memberId)){
				member.setAvatar(cutUrl);
				member.setImageServer(imageServer);
			}
			Member m = new Member();
			m.setIdentifier(memberId);
			m.setAvatar(cutUrl);
			m.setImageServer(imageServer);
			memberDao.updateMember(m);
		} else if (Integer.parseInt(type) == 2) {
			member.getFamilyObj().setAvatar(cutUrl);
			member.getFamilyObj().setImageServer(imageServer);
			Family mFamily = new Family();
			mFamily.setDoorplate(member.getFamily());
			mFamily.setAvatar(cutUrl);
			mFamily.setImageServer(imageServer);
			familyDao.updateFamily(mFamily);
		} else if (Integer.parseInt(type) == 3) {
			
			Member baby = new Member();
			baby.setIdentifier(memberId);
			baby.setAvatar(cutUrl);
			baby.setImageServer(imageServer);
			memberDao.updateMember(baby);
		}

		return imageServer+cutUrl;
	}

	@Override
	public List<Member> getMemberListByDoorplate(String doorplate)
			throws AppBusinessException {
		return memberDao.getMemberListByDoorplate(doorplate);
	}

	// 根据标识号删除宝宝信息
	@Override
	public void deleteBabyInfo(String identifier) throws AppBusinessException {
		memberDao.deleteBabyInfo(identifier);
	}

	@Override
	public void sendEmailToMember(String basePath, Member member)
			throws AppBusinessException {
		mailBiz.sendEmail(basePath, member);
	}

	/**
	 * 根据门牌号取得爸爸妈妈的集合
	 * @param doorplate			门牌号
	 * @throws AppBusinessException
	 */
	@Override
	public List<Member> getParentListByDoorplate(String doorplate)
			throws AppBusinessException {
		return memberDao.getParentListByDoorplate(doorplate);
	}

	@Override
	public String getHostPwdByDoorplate(String doorplate)
			throws AppBusinessException {
		return memberDao.getHostPwdByDoorplate(doorplate);
	}

	@Override
	public Member getHostInfoByDoorplate(String doorplate)
			throws AppBusinessException {
		return memberDao.getHostInfoByDoorplate(doorplate);
	}

}
